const IDKEY = "orderId";
function setOrder(id) {
  localStorage.setItem(IDKEY, id);
}
function getOrder() {
  return localStorage.getItem(IDKEY);
}
function generOrder() {
  const obj = {
    id: "" + Date.now() + Math.random().toString().slice(3, 6),
    expire: Date.now() + 1000 * 60 * 60 * 1,
  };
  setOrder(JSON.stringify(obj));
}

const order = JSON.parse(getOrder());

if (!order) {
  generOrder();
} else if (order.expire - Date.now() < 0) {
  generOrder();
}

const btn = document.querySelector("button");
btn.addEventListener("click", submitV2);

// 延时函数
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

let isDisabled = false;
/**
 * 提交
 */
async function submit() {
  localStorage.setItem("orderId", "123");
  isDisabled = true;
  btn.innerText = "加载中...";
  const url = await fetch("/api/pay")
    .then((resp) => resp.json())
    .then(({ data }) => data);

  location.href = url;
  await sleep(1000);
  isDisabled = false;
  btn.innerText = "点击进群";
}

async function submitV2() {
  // const { data } = await fetch("/api/weChaty/status").then((res) => res.json());
  const data = true;
  if (data) {
    fetch("/api/payCount");
    // 已经登录
    // location.href = `/pay.html?orderId=${getOrder()}&return=/code.html`;
    location.href = `/pay.html`;
  } else {
    location.href = "/login.html";
  }
}
const groupNameDom = document.querySelector(".group-name");
(async () => {
  try {
    const locationName = await fetch("/api/getGroupName").then((res) => {
      if (res.status !== 200) {
        return null;
      }
      return res.text();
    });
    if (!locationName) {
      throw new Error("获取群名失败");
    }

    groupNameDom.innerText = locationName + groupNameDom.innerText;
  } catch (error) {}
})();
